var express = require('express');
var router = express.Router();
const UserModel = require('../../models/UserModel')
const md5 = require('md5')

router.get('/reg', (req, res) => {
    res.render('auth/reg')
})

// 注册
router.post('/reg', async (req, res) => {
    // console.log(req.body);
   try {
        const data = await UserModel.create({...req.body, password: md5(req.body.password)})
        // console.log(data);
        res.render('success', {msg: '注册成功', url: '/login'})
   } catch (error) {
        res.status(500).send('注册失败')
   }
})

// 登录页面
router.get('/login', (req, res) => {
    res.render('auth/login')
})
// 登录提交
router.post('/login', async (req, res) => {
    const {username, password} = req.body
    try {
       const data = await UserModel.findOne({username: username, password: md5(password)})
       console.log(data);
       if (!data) {
        return res.send('账号或密码错误')
       }
    //    写入session
       req.session.username = data.username
       req.session._id = data._id
       res.render('success', {msg: '登陆成功', url: '/account'})
    } catch (error) { 
        res.status(500).send('登陆失败')
    }
})

// 退出登录
router.post('/logout', (req, res) => {
    req.session.destroy(() => {
        res.render('success', {msg: '推出成功', url: '/login'})
    })
    
})


module.exports = router;
